// 简单的小程序 WebSocket 信道封装
// const bmobSocketIo = require('../../utils/bmobSocketIo');

var that = this;
var Bmob = require('../../dist/Bmob-1.6.0.min.js');
const {
  $Message
} = require('../../dist/base/index');
var app = getApp();
var User1 = { nickName: "学术交流机器人", avatarUrl:"http://bmob-cdn-20131.b0.upaiyun.com/2018/06/27/2117b7cf4099a2d580db88dddfaff555.bmp"}

/**
 * 生成一条聊天室的消息的唯一 ID
 */
function msgUuid() {
  if (!msgUuid.next) {
    msgUuid.next = 0;
  }
  return 'msg-' + (++msgUuid.next);
}

/**
 * 生成聊天室的系统消息
 */
function createSystemMessage(content) {
  return {
    id: msgUuid(),
    type: 'system',
    content
  };
}

/**
 * 生成聊天室的聊天消息
 */
function createUserMessage(content, user, isMe) {
  return {
    id: msgUuid(),
    type: 'speak',
    content,
    user,
    isMe
  };
}

// 声明聊天室页面
Page({

  /**
   * 聊天室使用到的数据，主要是消息集合以及当前输入框的文本
   */
  data: {
    messages: [],
    inputContent: '',
    lastMessageId: 'none',
    msgObjectId: "",
    objectId: ""
  },

  /**
   * 页面渲染完成后，启动聊天室
   * */
  onReady() {
    let that = this;
    var user = app.globalData.userInfo
    console.log(app.globalData.userInfo.nickName)
    that.setData({
      objectId : app.globalData.authData.objectId,
      // objectId: "abcd123",
      User:user
    })

    wx.setNavigationBarTitle({
      title: '学术交流机器人'
    });
    // that.pushMessage(createUserMessage("这是一条自己发的信息", that.data.User, true));
    // that.pushMessage(createUserMessage("这是一条机器人他发的信息", User1, false));

    wx.connectSocket({
      url: "ws://soulcode.cn:8080/wxapp/websocket",
      success: function(res) {
        that.pushMessage(createSystemMessage('加入聊天成功'));
      }
    })

    //连接成功
    wx.onSocketOpen(function() {
      wx.sendSocketMessage({
        data: JSON.stringify({
          'RegisterFor': that.data.objectId,
          'text': "你好啊"
        })
      })
    })

    //接收数据
    wx.onSocketMessage(function(data) {

      var results = JSON.parse(data.data).results[0]
      console.log("Get data", JSON.parse(data.data).results[0]);
      var text;
      if (results.resultType == 'text') {
        text = results.values.text
      }
      else if (results.resultType == 'url'){
        text = results.values.url
      }
      else{
        text = '你说了啥哦，我都被你吓到了'
      }
      that.pushMessage(createUserMessage(text, User1, 0));
    })

    //连接失败
    wx.onSocketError(function() {
      console.log('websocket连接失败！');
    })
  },

  /**
   * 通用更新当前消息集合的方法
   */
  updateMessages(updater) {
    var messages = this.data.messages;
    updater(messages);

    this.setData({
      messages
    });

    // 需要先更新 messagess 数据后再设置滚动位置，否则不能生效
    var lastMessageId = messages.length ? messages[messages.length - 1].id : 'none';
    console.log(lastMessageId);
    this.setData({
      lastMessageId
    });
  },

  /**
   * 追加一条消息
   */
  pushMessage(message) {
    this.updateMessages(messages => messages.push(message));
  },

  /**
   * 替换上一条消息
   */
  amendMessage(message) {
    this.updateMessages(messages => messages.splice(-1, 1, message));
  },

  /**
   * 删除上一条消息
   */
  popMessage() {
    this.updateMessages(messages => messages.pop());
  },

  /**
   * 用户输入的内容改变之后
   */
  changeInputContent(e) {
    this.setData({
      inputContent: e.detail.value
    });
  },

  /**
   * 点击「发送」按钮，通过信道推送消息到服务器
   **/
  sendMessage(e) {
    let that = this
    if (that.data.inputContent) {
      wx.sendSocketMessage({
        data: JSON.stringify({
          'RegisterFor': that.data.objectId,
          'text': that.data.inputContent
        }),
        success: function() {
          that.pushMessage(createUserMessage(that.data.inputContent, that.data.User, 1));
          that.setData({
            inputContent: ''
          })
        },
        fail: function() {
          that.pushMessage(createSystemMessage('发送失败'));
        }
      })
    } else {
      that.pushMessage(createSystemMessage('请输入信息后发送'));
    }
  },
});



